import pandas as pd
from sklearn.preprocessing import StandardScaler

pd.set_option('display.max_columns', None)  # 显示所有列，无省略
pd.set_option('display.max_rows', None)     # 显示所有行
pd.set_option('display.max_colwidth', None) # 当列内容过长时也完整显示
pd.set_option('display.width', 2000)        # 设定输出窗口宽度，防止换行断行
import seaborn as sns
import matplotlib.pyplot as plt

churn = pd.read_csv('data/Customer Churn.csv')
# print(churn.info())
# print(churn.head())
churn = pd.get_dummies(churn) #处理数据，将字符串处理为数字
# print(churn.head())
# churn.drop(['xxx', 'yyy', 'zzz'], axis=1, inplace=True) #删除列方法
# print(churn.Churn.value_counts())
# print(churn.Churn.value_counts(1))

# print(churn.groupby('Churn').mean())

# sns.countplot(y='Tariff Plan',hue='Churn', data=churn)
# plt.show()
# 从中挑选几个特征
y = churn['Churn']
x = churn[['Complains', 'Charge  Amount', 'Seconds of Use', 'Frequency of use', 'Frequency of SMS', 'Distinct Called Numbers', 'Customer Value']]


from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)
# 特征工程-标准化
transfer = StandardScaler()
x_train = transfer.fit_transform(x_train)
x_test = transfer.transform(x_test)
# print(x_train)
#训练模型 逻辑回归
from sklearn.linear_model import LogisticRegression
# lr = LogisticRegression()
# lr.fit(x_train, y_train)
# #模型评估
# y_predict = lr.predict(x_test)
#计算准确率
from sklearn.metrics import accuracy_score
from sklearn.metrics import roc_auc_score
# print(accuracy_score(y_test, y_predict))
#
# print(roc_auc_score(y_test, y_predict))

# 调整权重
# lr = LogisticRegression(class_weight='balanced') #调整由于数据分布不均匀导致的权重问题
# lr.fit(x_train, y_train)
#模型评估
# y_predict = lr.predict(x_test)
# print(accuracy_score(y_test, y_predict))
# print(roc_auc_score(y_test, y_predict))

# K值交叉验证
from sklearn.model_selection import StratifiedKFold, GridSearchCV
k_fold = StratifiedKFold(n_splits=5, shuffle=True)
lr = LogisticRegression()
param_grid = {'solver': ['lbfgs', 'newton-cg', 'liblinear', 'sag'],
              'C': [0.001, 0.01, 1, 10, 100],
              'class_weight': ['balanced'],
              'max_iter': [500, 1000]}
search = GridSearchCV(lr, param_grid)
lr = search.fit(x_train, y_train)
print(lr.coef_)

print(search.score(x_test, y_test))